package com.ittao.taoaicodeai.ai.config;

import dev.langchain4j.model.chat.StreamingChatModel;
import dev.langchain4j.model.openai.OpenAiStreamingChatModel;
import jakarta.annotation.Resource;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

/**
 * 流式对话模型配置
 */
@Configuration
@ConfigurationProperties(prefix = "langchain4j.open-ai.streaming-chat-model")
@Data
public class StreamingChatModelConfig {

    @Resource
    private VipLimitConfig vipLimitConfig;

    // @Resource
    // private AiModelMonitorListener aiModelMonitorListener;

    // OpenAI API 基础 URL
    private String baseUrl;

    // OpenAI API 密钥
    private String apiKey;

    // 模型名称
    private String modelName;

    // 最大 token 数
    private Integer maxTokens;

    // 温度参数
    private Double temperature;

    // 是否记录请求
    private boolean logRequests = false;

    // 是否记录响应
    private boolean logResponses = false;

    /**
     * 流式对话模型 Bean，原型作用域
     */
    @Bean
    @Scope("prototype")
    public StreamingChatModel streamingChatModelPrototype() {
        return OpenAiStreamingChatModel.builder()
                .apiKey(apiKey)
                .baseUrl(baseUrl)
                .modelName(modelName)
                .maxTokens(maxTokens)
                .temperature(temperature)
                .logRequests(logRequests)
                .logResponses(logResponses)
                // .listeners(List.of(aiModelMonitorListener))
                .build();
    }

    /**
     * 根据用户角色创建流式对话模型
     * @param userRole 用户角色
     * @return 配置了对应限制的StreamingChatModel
     */
    public StreamingChatModel createStreamingChatModelForUser(String userRole) {
        VipLimitConfig.UserLimits limits = vipLimitConfig.getLimitsByRole(userRole);
        return OpenAiStreamingChatModel.builder()
                .apiKey(apiKey)
                .baseUrl(baseUrl)
                .modelName(modelName)
                .maxTokens(limits.getMaxTokens()) // 使用VIP配置的动态限制
                .temperature(temperature)
                .logRequests(logRequests)
                .logResponses(logResponses)
                // .listeners(List.of(aiModelMonitorListener))
                .build();
    }
}
